﻿using System;
using System.Linq;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint;
using System.Collections;
using System.Security.Permissions;
using ZhukBlogLinqExamples.FieldTypes.Employee.Controls;

namespace ZhukBlogLinqExamples.FieldTypes.Employee
{
    public class EmployeeFieldControlMulti : MultipleLookupField
    {
        [SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
        protected override void CreateChildControls()
        {
            if (IsFieldValueCached)
            {
                base.CreateChildControls();
            }
            else if (Field != null)
            {
                if (ControlMode != SPControlMode.Display)
                {
                    _picker = new EmployeePicker { CustomProperty = "1" };
                    Controls.Add(_picker);
                    SetFieldControlValue(Page.IsPostBack ? Value : ItemFieldValue);
                }

            }
        }

        public override void Validate()
        {
        }

        private EmployeePicker _picker;

        private void SetFieldControlValue(object value)
        {
            _picker.Entities.Clear();
            var list = new ArrayList();
            if (ControlMode == SPControlMode.New && _picker.Entities.Count == 0)
            {
                //DEFAULT VALUE
            }
            else
            {
                if (value != null && value.GetType().Name == typeof(string).Name)
                {
                    var val = new SPFieldLookupValueCollection((string)value);
                    list.AddRange((val).Select(l => l.ToPickerEntity()).ToArray());
                }
                else if (value is SPFieldLookupValue)
                {
                    list.Add(((SPFieldLookupValue)value).ToPickerEntity());
                }
                else if (value is SPFieldLookupValueCollection)
                {
                    list.AddRange(((SPFieldLookupValueCollection)value).Select(l => l.ToPickerEntity()).ToArray());
                }
            }
            _picker.UpdateEntities(list);
        }

        public override object Value
        {
            get
            {
                EnsureChildControls();
                var resolvedEntities = _picker.ResolvedEntities.Cast<PickerEntity>().Where(e => e.IsResolved);
                if (resolvedEntities.Count() == 0)
                    return null;
                //        if (resolvedEntities.Count() == 1)
                //        {
                //            var entity = resolvedEntities.First();
                //            return new SPFieldLookupValue(Convert.ToInt32(entity.Key), entity.DisplayText);
                //        }
                var entityCollection =
                    resolvedEntities.Select(e => new SPFieldLookupValue(Convert.ToInt32(e.Key), e.DisplayText));
                var fc = new SPFieldLookupValueCollection();
                fc.AddRange(entityCollection);
                return fc;
            }
            set
            {
                EnsureChildControls();
                SetFieldControlValue(value);
            }
        }

        public override void UpdateFieldValueInItem()
        {
            var val = string.Empty;
            ItemIds.Clear();
            if (_picker != null && _picker.ResolvedEntities.Count > 0)
                for (var i = 0; i < _picker.ResolvedEntities.Count; i++)
                {
                    var ent = _picker.ResolvedEntities[i] as PickerEntity;
                    if (ent == null) continue;
                    val = i == 0 
                        ? string.Format("{0};#{1}", ent.Key, ent.DisplayText) 
                        : string.Format("{0};#{1};#{2}", val, ent.Key, ent.DisplayText);
                    ItemIds.Add(Convert.ToInt32(ent.Key));
                }
            ItemFieldValue = new SPFieldLookupValueCollection(val);
            base.UpdateFieldValueInItem();
        }
    }
}
